from datetime import datetime,timezone, timedelta
from io import BytesIO
import os
import uuid
from django.conf import settings
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import redis
from yida_app_service.models import HzfwQrCode
from yida_app_service.utils.hzfw_utils import gen_qr_code, update_report_info
from reportservice.helpers import ApiResponse
import json
from dingtalk_service.yida_client_jianhong import YidaClient
import requests
import qrcode
from reportlab.pdfgen import canvas
from PyPDF2 import PdfWriter, PdfReader
from reportlab.lib.utils import ImageReader
from urllib.parse import unquote
from oss_service.views import bucket
import pandas as pd
from io import BytesIO


org_id = "A22F53516783496ABF4D77FE6E118034"
admin_user_id = "0148353311656032"
r = redis.StrictRedis(host='10.8.0.83', port=6379, db=0)


@csrf_exempt
@require_http_methods(["POST"])
def apply_hzfw_qr(request):
    datasource: dict[str, any] = json.loads(request.body)
    report_code = datasource["reportCode"]
    file_url = datasource["fileUrl"]
    full_download_url = YidaClient.get_full_download_url(
        user_id=admin_user_id, download_url=file_url, base_url=r"https://yp7lri.aliwork.com")
    response = requests.get(full_download_url.body.result)
    if response.status_code == 200:
        pdf_content = BytesIO(response.content)
        # report_code = f"{report_code}"
        try:
            res = gen_qr_code(org_id, report_code)
        except Exception as e:
            return ApiResponse.fail(message=f"生成二维码失败,{e}")
        if res["code"] == "ok":
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=10,
                border=4,
            )
            qr.add_data(res["qrcodestr"])
            qr.make(fit=True)
            img = qr.make_image(fill_color="black", back_color="white")

            qr_io = BytesIO()
            img.save(qr_io, format="PNG")
            qr_io.seek(0)  # 移动到流的开头
            packet = BytesIO()
            c = canvas.Canvas(packet)
            qr_x = 50
            qr_y = 50
            qr_size = 100
            qr_image = ImageReader(qr_io)
            c.drawImage(qr_image, qr_x, qr_y, qr_size, qr_size)
            c.save()
            packet.seek(0)
            reprt_pdf = PdfReader(pdf_content)
            qr_pdf = PdfReader(packet)
            output = PdfWriter()
            page = reprt_pdf.pages[0]
            page.merge_page(qr_pdf.pages[0])
            output.add_page(page)
            for i in range(1, len(reprt_pdf.pages)):
                output.add_page(reprt_pdf.pages[i])
            pdf_path = f"jianhong/{uuid.uuid4()}.pdf"
            tmp_path = f"{os.path.join(settings.BASE_DIR, r'data')}/xiaming_tmp/{pdf_path}"
            with open(tmp_path, "wb") as outputStream:
                output.write(outputStream)
            bucket.put_object_from_file(pdf_path, tmp_path)
            sign_url = bucket.sign_url('GET', pdf_path, 3600)
            return ApiResponse.success(sign_url)
        else:
            return ApiResponse.fail(res["msg"])

@csrf_exempt
@require_http_methods(["POST"])
def apply_hzfw_qr_v2(request):
    datasource: dict[str, any] = json.loads(request.body)
    report_code = datasource["reportCode"]
    file_url = datasource["fileUrl"]
    default_position = [{
                          "page":1,
                          "posx":50,
                          "posy":50,
                          "size":100
                      }]
    positions = datasource.get("position",default_position)

    full_download_url = YidaClient.get_full_download_url(
        user_id=admin_user_id, download_url=file_url, base_url=r"https://yp7lri.aliwork.com")
    response = requests.get(full_download_url.body.result)
    if response.status_code == 200:
        pdf_content = BytesIO(response.content)
        qr_code = HzfwQrCode.objects.filter(report_code=report_code, org_id=org_id, is_uploaded=False).order_by('-id').first()
        if not qr_code:
            try:
                res = gen_qr_code(org_id, report_code)
            except Exception as e:
                return ApiResponse.fail(message=f"生成二维码失败,{e}")
            if res["code"] == "ok":
                qr_data = res["qrcodestr"]
                qr_code = HzfwQrCode(report_code=report_code,
                                      org_id=org_id,
                                      company_name="jianhong",
                                      qr_code_content=qr_data)
        qr_data = qr_code.qr_code_content
        reprt_pdf = PdfReader(pdf_content)
        output = PdfWriter()
        for position in positions:
            page_num = int(position["page"])
            qr_x = int(position["posx"])
            qr_y = int(position["posy"])
            qr_size = int(position["size"])
            qr = qrcode.QRCode(
                version=1,
                error_correction=qrcode.constants.ERROR_CORRECT_L,
                box_size=10,
                border=4,
            )
            qr.add_data(qr_data)
            qr.make(fit=True)
            img = qr.make_image(fill_color="black", back_color="white")
            qr_io = BytesIO()
            img.save(qr_io, format="PNG")
            qr_io.seek(0)  # 移动到流的开头
            if page_num - 1 < len(reprt_pdf.pages):
                # 绘制 QR 码至指定页面
                packet = BytesIO()
                c = canvas.Canvas(packet)
                qr_image = ImageReader(qr_io)
                c.drawImage(qr_image, qr_x, qr_y, qr_size, qr_size)
                c.save()

                # 合并 QR 码页面到原始 PDF 页面
                packet.seek(0)
                qr_pdf = PdfReader(packet)
                reprt_pdf.pages[page_num - 1].merge_page(qr_pdf.pages[0])
        for page in reprt_pdf.pages:
            output.add_page(page)
        pdf_path = f"jianhong/{uuid.uuid4()}.pdf"
        tmp_path = f"{os.path.join(settings.BASE_DIR, r'data')}/xiaming_tmp/{pdf_path}"
        with open(tmp_path, "wb") as outputStream:
            output.write(outputStream)
        bucket.put_object_from_file(pdf_path, tmp_path)
        qr_code.pdf_path = pdf_path
        qr_code.save()
        sign_url = bucket.sign_url('GET', pdf_path, 3600)
        return ApiResponse.success(sign_url)
    else:
        return ApiResponse.fail(res["msg"])

def date_format(value):
    try:
        date = datetime.fromtimestamp(value / 1000, timezone.utc)
        date += timedelta(hours=8)
        return date.strftime('%Y-%m-%d')
    except ValueError:
        return None

@csrf_exempt
@require_http_methods(["POST"])
def upload_hzfw_data(request):
    datasource = json.loads(request.body)
    try:
        area_name = datasource["area_name"]
        report_code = datasource["report_code"]
        report_info = datasource["report_info"]
        report_info["YPBH"] = report_info.get("YPBH","-")
        if not report_info.get("YPBH"):
            report_info["YPBH"] = "-"
        report_info["BGRQ"] = date_format(report_info["BGRQ"])
        report_info["JCRQ"] = date_format(report_info["JCRQ"])
        if report_info.get("JCRQ2"):
            report_info["JCRQ2"] = date_format(report_info["JCRQ2"])
        report_info["JCNR"] = ";".join(report_info["JCNR"])
        res = update_report_info(org_id,"",area_name,report_code,report_info)
        if "上传成功" in res:
            qr_code = HzfwQrCode.objects.filter(report_code=report_code, org_id=org_id, is_uploaded=False).order_by('-id').first()
            # qr_code = HzfwQrCode.objects.get(report_code=report_code,org_id=org_id,is_uploaded=False)
            qr_code.is_uploaded = True
            qr_code.save()
            YidaClient.update_form_data_by_field("FORM-1FAA7C34632F4274919DA007B7191575G6PJ",admin_user_id,{"textField_lqqbd27b":report_code},{"selectField_ltirw8ui":"已上传"})
            return ApiResponse.success(res)
        else:
            return ApiResponse.fail(res,400)
    except KeyError:
        return ApiResponse.fail("字段必传校验失败",400)


@csrf_exempt
@require_http_methods(["GET"])
def upload_price_shell(request):
    # 从 GET 请求参数中获取下载链接，并解码该链接。unquote 用于处理 URL 编码。
    download_url = unquote(request.GET.get('download_url'))
    project_id = request.GET.get('project_id')
    full_download_url = YidaClient.get_full_download_url(
        user_id=admin_user_id, download_url=download_url)

    url = full_download_url.body.result  # 从完整的下载链接响应中提取实际的文件下载链接。
    with requests.Session() as session:  # 使用 requests 库创建一个会话对象，用于发送 HTTP 请求。
        response = session.get(url)  # 发送 GET 请求以获取文件内容。
        if response.status_code == 200:
            file_content = response.content  # 从响应中获取文件的内容。
            bucket.put_object(
                rf"jianhong/{project_id}/price_shell.xlsx", file_content)
            return ApiResponse.success()
    return ApiResponse.fail("清单上传失败")


@csrf_exempt
@require_http_methods(["GET"])
def prepare_price_shell(request):
    project_id = request.GET.get('project_id')
    price_shell_path = f"jianhong/{project_id}/price_shell.xlsx"
    exist = bucket.object_exists(price_shell_path)
    if (exist):
        price_shell_content = bucket.get_object(price_shell_path).read()
        excel_file = BytesIO(price_shell_content)
        df = pd.read_excel(excel_file)
        for index, row in df.iterrows():
            redis_key = f"{str(row['检测项目'])}-{str(row['检测参数'])}"
            redis_value = str(row['费用'])
            # 存储到Redis
            r.set(f"jianhong:{project_id}:{redis_key}", redis_value)
        return ApiResponse.success("success")
    else:
        return ApiResponse.fail("未找到价格清单")


@csrf_exempt
@require_http_methods(["GET"])
def get_single_price(request):
    project_id = request.GET.get('project_id')
    param_name = request.GET.get('param_name')
    param_key = rf"jianhong:{project_id}:{param_name}"
    price = r.get(param_key)
    if price:
        price = int(price.decode())
        return ApiResponse.success(price)
    else:
        return ApiResponse.fail("未找到价格")


@csrf_exempt
@require_http_methods(["POST"])
def gen_total_price(request):
    datasource: dict[str, any] = json.loads(request.body)
    project_id = datasource["project_id"]
    param_names = datasource['param_names']
    res_price = 0
    for param_name in param_names:
        param_key = rf"jianhong:{project_id}:{param_name}"
        price = r.get(param_key)
        if price:
            price = int(price.decode())
            res_price = res_price + price
        else:
            ApiResponse.fail("未找到价格")
    return ApiResponse.success(res_price)